#!/usr/bin/env python
# -*- coding: utf-8 -*-
# vi: ts=4 expandtab
#
# Copyright (C) 2012 KT
#
# Author: Choonho Son <choonho.son@kt.com>
#

import subprocess
from cloudcfg.lib.cmd import Cmd
from cloudcfg.lib.cmd_fstab import cmd_fstab

__version__="1.0"

class cmd_nfs(Cmd):
	def __init__(self, logger):
		Cmd.__init__(self,logger)

	def create_volume(self, params):
		"""
		create logical volume
		format disk
		
		@params (dictionary)
		dev : /dev/xvdb
		vgname : volume group name
		lvname : logical volume name
		fs : formatting file system
		"""
		p = params
		cmd = [ 'pvcreate', p['dev'] ]
		self.run(cmd)

		cmd = [ 'vgcreate', p['vgname'], p['dev'] ]
		self.run(cmd)

		cmd = [ 'lvcreate', '-l', '100%VG', '-n', p['lvname'], p['vgname'] ]
		self.run(cmd)
		
		path = "/dev/%s/%s" % (p['vgname'], p['lvname'])		
                cmd = [ 'lvchange', '-ay', path]
		self.run(cmd)

		cmd = [ p['fs'], path ]
		self.run(cmd)

		cmd = [ 'mount', path, p['mnt_point'] ]
		self.run(cmd)

		#update /etc/fstab
		p2 = {'dev'    : path,
		      'mnt'    : p['mnt_point'],
		      'fstype' : p['fs'],
		      'options': 'rw',
		      }
		cmd2 = cmd_fstab(self.logger)
		tf = cmd2.update_fstab(p2)
		self.logger.debug("Update /etc/fstab (%s)" % tf)
		
		      
	def update_export(self, params):
		"""
		update /etc/exports

		@params (dictionary)
		path : export path
		"""
		
		# ToDO: duplication check

		fp = open('/etc/exports','a')
		cmd = "\n%s %s(%s)" % (params['path'],'0.0.0.0/0.0.0.0','rw,no_root_squash')
		self.logger.debug("add NFS config: %s" % cmd)
		fp.write(cmd)
		fp.close()

	def client_mount(self, params):
		"""
		mount
		@param : dictionary
		mount.nfs <server>:<path> <mnt_point>
		"""
		p = params
		cmd = ['mount.nfs',"%s:%s" % (p['server'],p['path']), p['mnt_point']]
		self.run(cmd)

	def client_umount(self, params):
		"""
		mount
		@param : dictionary
		mount.nfs <server>:<path> <mnt_point>
		"""
		p = params
		cmd = ['umount',"%s" % p['mnt_point'] ]
		self.run(cmd)
															

	def updateAutomaster(self, params):
		msg = "%s" % params['auto.master']
		fp = open('/etc/auto.master','w')
		fp.write(msg)
		fp.close()

	def updateAutohome(self, params):
		msg = "%s" % params['auto.home']
		fp = open('/etc/auto.home','w')
		fp.write(msg)
		fp.close()
		
		
		
